//
//  HJAccountSettingController.m
//  KaiChat
//
//  Created by lx on 2024/1/17.
//

#import "HJAccountSettingController.h"
#import "HJTitleRedPointCell.h"
#import "HJUIAlertController.h"
#import "HJMinePresent.h"
#import "HJUserModel.h"
#import "HJGoogleAuthenticator.h"
#import "HJAppleAuthenticator.h"
#import "HJSetPasswordVerifyController.h"

@interface HJAccountSettingController ()<HJAppleAuthenticatorDelegate>

@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) HJAppleAuthenticator *appleAuthenticator;
@property (nonatomic, strong) HJCellModel *googleModel;
@property (nonatomic, strong) HJCellModel *appleModel;
@property (nonatomic, strong) HJCellModel *passwordModel;

@end

@implementation HJAccountSettingController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationBar.title = @"Account Security";
    self.navigationBar.lineView.hidden = YES;
    
    [self.tableView registerClass:HJTitleRedPointCell.class forCellReuseIdentifier:@"HJTitleRedPointCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = cellHeight;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(KNavBarHight);
        make.bottom.offset(0);
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCellModel *model = self.datas[indexPath.row];
    HJTitleRedPointCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJTitleRedPointCell" forIndexPath:indexPath];
    cell.model = model;
    cell.selectionStyle = model.showArrow ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJCellModel *model = self.datas[indexPath.row];
    
    if (model.showRedPoint) {
        model.showRedPoint = NO;
        HJTitleRedPointCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.model = model;
        dispatch_async_sql_queue(^{
            HJUserModel *userModel = [HJUserModel currentAccountModel];
            if ([model.identifier isEqualToString:@"google"]) {
                userModel.bindGoogleRead = YES;
            } else if ([model.identifier isEqualToString:@"apple"]) {
                userModel.bindAppleRead = YES;
            }
            [userModel bg_saveOrUpdate];
            HJUserInfo.model = userModel;
            
            dispatch_async_main_queue(^{
                [[NSNotificationCenter defaultCenter] postNotificationName:didClickBindingGoogleOrAppleNotification object:nil];
            });
        });
    }

    if ([model.identifier isEqualToString:@"password"]) {
        HJSetPasswordVerifyController *verifyIdentityController = [[HJSetPasswordVerifyController alloc] init];
        if (HJUserInfo.model.hasPassword) {
            verifyIdentityController.type = HJSetPasswordTypeChange;
        } else {
            verifyIdentityController.type = HJSetPasswordTypeNone;
        }
        TJWeakify(self)
        [verifyIdentityController setSetComplete:^{
            [HJMinePresent loadUserInfoComplete:^(HJUserModel * _Nullable userModel) {
                if (userModel.hasPassword) {
                    weakself.passwordModel.detailText = @"Change";
                    weakself.passwordModel.detailTextColor = UIColor.tj_868391Color;
                } else {
                    weakself.passwordModel.detailText = @"Not set";
                    weakself.passwordModel.detailTextColor = UIColor.tj_BEBDCAColor;
                }
                [weakself.tableView reloadData];
            }];
        }];
        [self.navigationController pushViewController:verifyIdentityController];
        return;
    }
    
    if ([model.identifier isEqualToString:@"apple"]) {
        if (!isEmptyString(HJUserInfo.model.appleUserId)) return;
        [self.appleAuthenticator signInWithWithWindow:self.view.window];
        return;
    }
    
    if ([model.identifier isEqualToString:@"google"]) {
        
        if (!isEmptyString(HJUserInfo.model.googleEmail)) return;

        [HJGoogleAuthenticator bindingWithPresentingViewController:self completion:^(GIDGoogleUser * _Nonnull user, NSError * _Nonnull error) {
            
            if (error) {
                [HJHUD showMessage:error.localizedFailureReason];
                return;
            }
            
            [HJHUD showLoadingInView:self.view];
            [HJMinePresent bindGoogle:user.profile.email token:user.idToken.tokenString complete:^(NSError * _Nullable error) {
                if (!error) {
                    dispatch_async_sql_queue(^{
                        HJUserModel *userModel = [HJUserModel currentAccountModel];
                        userModel.googleEmail = user.profile.email;
                        userModel.googleUserId = user.userID;
                        [userModel bg_saveOrUpdate];
                        HJUserInfo.model = userModel;
                    });
                    
                    self.googleModel.detailText = @"Already linked";
                    self.googleModel.detailTextColor = UIColor.tj_868391Color;
                    self.googleModel.showArrow = NO;
                    [self.tableView reloadData];
                }
            }];
        }];
        return;
    }
    
    if ([model.identifier isEqualToString:@"aeactivate"]) {
        [self.navigationController pushViewControllerWithName:@"HJCancellationController"];
        return;
    }
}
 

- (HJAppleAuthenticator *)appleAuthenticator {
    if (!_appleAuthenticator) {
        _appleAuthenticator = [[HJAppleAuthenticator alloc] init];
        _appleAuthenticator.delegate = self;
    }
    return _appleAuthenticator;
}

- (void)appleAuthenticator:(HJAppleAuthenticator *)manager didCompleteWithError:(NSError *)error {
    NSLog(@"appleAuthenticatorerror = %@",error);
    [HJHUD showMessage:error.localizedFailureReason];
}

- (void)appleAuthenticator:(HJAppleAuthenticator *)manager didCompleteWithResult:(HJAppleSignInResult *)result {
    NSLog(@"didCompleteWithResult = %@",result);
    [HJHUD showLoadingInView:self.view];
    [HJMinePresent bindApple:result.user.userID token:result.user.identityToken complete:^(NSError * _Nullable error) {
        if (!error) {
            dispatch_async_sql_queue(^{
                HJUserModel *userModel = [HJUserModel currentAccountModel];
                userModel.appleUserId = result.user.userID;
                [userModel bg_saveOrUpdate];
                HJUserInfo.model = userModel;
            });
            self.appleModel.detailText = @"Already linked";
            self.appleModel.detailTextColor = UIColor.tj_868391Color;
            self.appleModel.showArrow = NO;
            [self.tableView reloadData];
        }
    }];
}

- (void)appleAuthenticator:(HJAppleAuthenticator *)manager appleIdStateChanged:(NSDictionary *)info {
    NSLog(@"appleAuthenticator = %@",info);
}

- (NSArray *)datas {
    if (!_datas) {
        
        NSMutableArray *datas = [NSMutableArray array];
        datas = @[
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"google";
                model.text = @"Google";
                if (isEmptyString(HJUserInfo.model.googleEmail)) {
                    model.detailText = @"Not linked";
                    model.detailTextColor = UIColor.tj_BEBDCAColor;
                    model.showRedPoint = !HJUserInfo.model.bindGoogleRead;
                    model.showArrow = YES;
                } else {
                    model.detailText = @"Already linked";
                    model.detailTextColor = UIColor.tj_868391Color;
                    model.showRedPoint = NO;
                    model.showArrow = NO;
                    dispatch_async_sql_queue(^{
                        HJUserModel *userModel = [HJUserModel currentAccountModel];
                        userModel.bindGoogleRead = YES;
                        [userModel bg_saveOrUpdate];
                        HJTools.tool.userModel = userModel;
                    });
                }
                self.googleModel = model;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"apple";
                model.text = @"Apple";
                if (isEmptyString(HJUserInfo.model.appleUserId)) {
                    model.detailText = @"Not linked";
                    model.detailTextColor = UIColor.tj_BEBDCAColor;
                    model.showRedPoint = !HJUserInfo.model.bindAppleRead;
                    model.showArrow = YES;
                } else {
                    model.detailText = @"Already linked";
                    model.detailTextColor = UIColor.tj_868391Color;
                    model.showArrow = NO;
                    dispatch_async_sql_queue(^{
                        HJUserModel *userModel = [HJUserModel currentAccountModel];
                        userModel.bindAppleRead = YES;
                        [userModel bg_saveOrUpdate];
                        HJTools.tool.userModel = userModel;
                    });
                }
                self.appleModel = model;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.text = @"Account password";
                model.identifier = @"password";
                if (HJUserInfo.model.hasPassword) {
                    model.detailText = @"Change";
                    model.detailTextColor = UIColor.tj_868391Color;
                } else {
                    model.detailText = @"Not set";
                    model.detailTextColor = UIColor.tj_BEBDCAColor;
                }
                self.passwordModel = model;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"aeactivate";
                model.text = @"Delete account";
                model.controllerName = @"HJCancellationController";
            }],
        ].mutableCopy;
        
        if (isHiddenAppleServe()) {
            dispatch_async_sql_queue(^{
                HJUserModel *userModel = [HJUserModel currentAccountModel];
                userModel.bindAppleRead = YES;
                [userModel bg_saveOrUpdate];
                HJTools.tool.userModel = userModel;
            });
            [datas removeObject:self.appleModel];
        }
        _datas = datas;
    }
    return _datas;
}
 
@end
